import { Document, Packer, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell, WidthType} from "docx";
import { saveAs } from "file-saver";

export async function exportReportToWord(data, fileName) {
  // 公共函数：生成段落
  const createParagraph = (text, opts = {}) =>
      new Paragraph({
        children: [new TextRun({ text, ...opts })],
        spacing: { after: 200 },
      });

  // 转换API数据结构为Word导出所需格式
  const taskBatch = data.taskBatch;
  const detectImageResults = data.detectImageResults || [];

  // 创建缺陷详情表格
  const defectRows = [];

  // 表头
  defectRows.push(
      new TableRow({
        children: [
          new TableCell({ children: [createParagraph("图片序号", { bold: true })] }),
          new TableCell({ children: [createParagraph("缺陷类型", { bold: true })] }),
          new TableCell({ children: [createParagraph("缺陷位置", { bold: true })] }),
          new TableCell({ children: [createParagraph("面积占比", { bold: true })] }),
          new TableCell({ children: [createParagraph("置信度", { bold: true })] }),
          new TableCell({ children: [createParagraph("严重程度", { bold: true })] }),
        ],
      })
  );

  // 添加缺陷数据行
  detectImageResults.forEach(image => {
    try {
      const defects = JSON.parse(image.detectionJson || "[]");
      defects.forEach((defect, index) => {
        defectRows.push(
            new TableRow({
              children: [
                new TableCell({ children: [createParagraph(image.imageIndex.toString())] }),
                new TableCell({ children: [createParagraph(defect.class_name || "未知")] }),
                new TableCell({ children: [createParagraph(`(${defect.bbox?.x1}, ${defect.bbox?.y1}) - (${defect.bbox?.x2}, ${defect.bbox?.y2})`)] }),
                new TableCell({ children: [createParagraph(`${defect.area_percentage}%`)] }),
                new TableCell({ children: [createParagraph(defect.confidence?.toString() || "0")] }),
                new TableCell({ children: [createParagraph(defect.severity?.level || "未知")] }),
              ],
            })
        );
      });
    } catch (e) {
      console.error("解析缺陷数据失败:", e);
    }
  });

  const defectTable = new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: defectRows,
  });

  // Word 文档结构
  const doc = new Document({
    sections: [
      {
        children: [
          createParagraph("检测报告", { bold: true, size: 32 }),
          createParagraph(`编号：${taskBatch.id}`),
          createParagraph(`时间：${taskBatch.completedAt}`),
          createParagraph(`模型：${taskBatch.detectionModel}`),
          createParagraph(`检测数量：${taskBatch.imageCount}`),
          createParagraph(`缺陷总数：${taskBatch.totalDefects}`),
          createParagraph(`合格率：${taskBatch.passRate}%`),
          createParagraph(`最终评分：${taskBatch.qualityScore}`),

          new Paragraph({
            text: "一、总体分析",
            heading: HeadingLevel.HEADING_1,
          }),
          createParagraph(taskBatch.batchSummary),

          new Paragraph({
            text: "二、图片详情",
            heading: HeadingLevel.HEADING_1,
          }),
          ...detectImageResults.map((image) => [
            new Paragraph({
              text: `图片序号：${image.imageIndex}`,
              heading: HeadingLevel.HEADING_2,
            }),
            // 添加可点击的原图链接
            new Paragraph({
              children: [
                new TextRun({
                  text: "原图预览:",
                  bold: true
                }),
                new TextRun(" "),
                new TextRun({
                  text: image.rawImageUrl || '无',
                  underline: {},
                  color: "0000FF",
                  link: image.rawImageUrl || ''
                })
              ],
              spacing: { after: 150 }
            }),
            createParagraph(`等级：${image.qualityGrade}`),
            createParagraph(`质量得分：${image.qualityScore}`),
            createParagraph(`风险等级：${image.riskLevel}`),
            createParagraph(`缺陷数：${image.detectionCount}`),
            createParagraph(`是否合格：${image.isAcceptable ? "是" : "否"}`),
            createParagraph(`总结：${image.imageSummary || image.gradeDescription}`),
          ]).flat(),

          new Paragraph({
            text: "三、缺陷详情",
            heading: HeadingLevel.HEADING_1,
          }),
          defectTable,

          new Paragraph({
            text: "四、改进建议",
            heading: HeadingLevel.HEADING_1,
          }),
          ...(taskBatch.overallSuggestions || "").split("\n").map((line) => createParagraph(line)),
        ],
      },
    ],
  });

  // 下载 Word
  const blob = await Packer.toBlob(doc);
  saveAs(blob, `${fileName}.docx`);
}
